package com.yuanzi.base.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化反序列化工具类
 * @author chengshx
 * @date 2017年5月8日
 */
public class SerializeUtils {

	/**
	 * 对象序列化
	 * @param object
	 * @return
	 */
	public static byte[] serialize(Object object) {
		ObjectOutputStream oos = null;
		ByteArrayOutputStream bos = null;
		try {
			// 序列化
			bos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(bos);
			oos.writeObject(object);
			byte[] bytes = bos.toByteArray();
			return bytes;
		} catch (Exception e) {
			LogUtils.error(SerializeUtils.class, "",e);
		} finally {
			try {
				bos.close();
				oos.close();
			} catch (IOException e) {
				LogUtils.error(SerializeUtils.class, "",e);
			}
			
		}
		return null;
	}

	/**
	 * 字节数组反序列化为对象
	 * @param bytes
	 * @return
	 */
	public static Object unserialize(byte[] bytes) {
		ByteArrayInputStream bis = null;
		ObjectInputStream ois = null;
		try {
			// 反序列化
			bis = new ByteArrayInputStream(bytes);
			ois = new ObjectInputStream(bis);
			Object obj = ois.readObject();
			return obj;
		} catch (Exception e) {
			LogUtils.error(SerializeUtils.class, "",e);
		} finally{
			try {
				bis.close();
				ois.close();
			} catch (IOException e) {
				LogUtils.error(SerializeUtils.class, "",e);
			}
		}
		return null;
	}
}
